
import { reactive } from "@vue/reactivity";
import { onMounted } from "@vue/runtime-core";
import { onBeforeRouteUpdate, useRoute, useRouter } from "vue-router";


export default function () {

    const route = useRoute();
    const router = useRouter();

    const data = reactive({
        tabsIndex: '',
        tabs: [
            // {title: '标题',name: '标识'}
        ]
    }
    );

    function swatchTab(item) {
        data.tabsIndex = item.name;
        router.push(item.name);
    }
    function closeTab(item) {
        let i = data.tabs.findIndex(x => x.name == item.name);
        data.tabs.splice(i, 1);
        if(item.name==data.tabsIndex){
            router.replace('/admin');
        }
    }
    function closeLeftTabs() {
        let i = data.tabs.findIndex(x => x.name == data.tabsIndex);
        data.tabs.splice(0, i);
    }
    function closeRightTabs() {
        let i = data.tabs.findIndex(x => x.name == data.tabsIndex);
        data.tabs.splice(i + 1, data.tabs.length);
    }
    function closeAllTabs() {
        data.tabs.length = 0;
    }
    function closeOtherTabs() {
        let i = data.tabs.findIndex(x => x.name == data.tabsIndex);
        data.tabs.splice(0, i);
        data.tabs.splice(1, data.tabs.length);
    }
    onMounted(() => {
        data.tabs.push({
            title: route.meta.title,
            name: route.path
        })
        data.tabsIndex = route.path;
    })
    onBeforeRouteUpdate((to, from) => {
        if (data.tabs.findIndex(x => x.name == to.path) < 0) {
            data.tabs.push({
                title: to.meta.title,
                name: to.path
            });
        }
        data.tabsIndex = to.path;
    })

    return {
        data,
        swatchTab,
        closeTab,
        closeLeftTabs,
        closeRightTabs,
        closeAllTabs,
        closeOtherTabs
    }
}